<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建用户 - 管理员专用</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .create-user-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 500px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 14px;
        }

        .user-info {
            background: #f5f5f5;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
        }

        .user-info strong {
            color: #667eea;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group input:disabled {
            background: #f5f5f5;
            color: #999;
        }

        .form-group .hint {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .employee-info {
            background: #e3f2fd;
            padding: 12px;
            border-radius: 8px;
            margin-top: 10px;
            display: none;
        }

        .employee-info p {
            margin: 5px 0;
            font-size: 13px;
            color: #555;
        }

        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 15px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #f5f5f5;
        }

        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
            font-size: 14px;
        }

        .message.success {
            background: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #4caf50;
        }

        .message.error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #f44336;
        }

        .message.show {
            display: block;
        }

        .required {
            color: red;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="create-user-container">
        <div class="header">
            <h1>👤 创建用户</h1>
            <p>管理员专用功能</p>
        </div>

        <div class="user-info" id="currentUserInfo">
            当前登录：<strong id="currentUsername"></strong> (<span id="currentUserRole">加载中...</span>)
        </div>

        <div class="message" id="message"></div>

        <form id="createUserForm">
            <div class="form-group">
                <label>用户类型 <span class="required">*</span></label>
                <select id="userType" name="userType" required>
                    <option value="0">子管理员</option>
                    <option value="1" id="adminOption" style="display:none;">管理员</option>
                </select>
                <div class="hint" id="userTypeHint">子管理员可以绑定员工或手动设置用户名密码</div>
            </div>

            <!-- 普通用户：选择绑定方式 -->
            <div id="normalUserFields">
                <div class="form-group">
                    <label>绑定方式</label>
                    <select id="bindType" name="bindType">
                        <option value="employee">绑定员工（用身份证号登录）</option>
                        <option value="manual">不绑定员工（手动设置用户名密码）</option>
                    </select>
                    <div class="hint">绑定员工后使用员工身份证号作为用户名；不绑定则手动设置用户名密码</div>
                </div>

                <!-- 绑定员工选项 -->
                <div id="bindEmployeeFields">
                    <div class="form-group">
                        <label>选择员工 <span class="required">*</span></label>
                        <select id="employeeId" name="employeeId" size="8" style="height: auto; padding: 8px;">
                            <option value="">-- 加载中... --</option>
                        </select>
                        <div class="hint">下拉列表显示：姓名 - 身份证号 - 部门。选择员工后将使用身份证号作为用户名</div>
                    </div>

                    <div class="employee-info" id="employeeInfo">
                        <p><strong>已选择员工信息：</strong></p>
                        <p>👤 姓名：<span id="employeeName"></span></p>
                        <p>🆔 身份证号（用户名）：<span id="employeeIdCard" style="color: #2196F3; font-weight: bold;"></span></p>
                        <p>🏢 部门：<span id="employeeDept"></span></p>
                        <p>💼 岗位：<span id="employeePos"></span></p>
                        <p>🔒 默认密码：<span style="color: #f44336; font-weight: bold;">88889999</span></p>
                    </div>
                </div>

                <!-- 手动输入选项 -->
                <div id="manualInputFields" class="hidden">
                    <div class="form-group">
                        <label>用户名 <span class="required">*</span></label>
                        <input type="text" id="normalUsername" name="normalUsername" placeholder="请输入用户名（字母、数字、下划线）">
                        <div class="hint">用户名只能包含字母、数字和下划线，长度3-50位</div>
                    </div>

                    <div class="form-group">
                        <label>密码 <span class="required">*</span></label>
                        <input type="password" id="normalPassword" name="normalPassword" placeholder="至少6位密码">
                    </div>

                    <div class="form-group">
                        <label>确认密码 <span class="required">*</span></label>
                        <input type="password" id="normalConfirmPassword" name="normalConfirmPassword" placeholder="再次输入密码">
                    </div>
                </div>
            </div>

            <!-- 管理员用户：手动输入 -->
            <div id="adminUserFields" class="hidden">
                <div class="form-group">
                    <label>用户名 <span class="required">*</span></label>
                    <input type="text" id="adminUsername" name="adminUsername" placeholder="请输入用户名（字母、数字、下划线）">
                    <div class="hint">用户名只能包含字母、数字和下划线，长度3-50位</div>
                </div>

                <div class="form-group">
                    <label>密码 <span class="required">*</span></label>
                    <input type="password" id="adminPassword" name="adminPassword" placeholder="至少6位密码">
                </div>

                <div class="form-group">
                    <label>确认密码 <span class="required">*</span></label>
                    <input type="password" id="confirmPassword" name="confirmPassword" placeholder="再次输入密码">
                </div>
            </div>

            <div class="form-group">
                <label>邮箱（选填）</label>
                <input type="email" id="email" name="email" placeholder="用于找回密码">
            </div>

            <div class="form-group">
                <label>手机号（选填）</label>
                <input type="tel" id="phone" name="phone" placeholder="11位手机号">
            </div>

            <button type="submit" class="btn btn-primary">创建用户</button>
            <button type="button" class="btn btn-secondary" onclick="window.location.href='home.html'">返回首页</button>
        </form>
    </div>

    <script>
        const API_BASE_URL = '/api/user';
        let employees = [];
        let currentUserLevel = 0; // 当前用户权限级别

        // 页面加载时检查登录状态和权限
        window.addEventListener('DOMContentLoaded', async () => {
            await checkLoginAndPermission();
            await loadEmployees();
        });

        // 检查登录状态和管理员权限
        async function checkLoginAndPermission() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            if (!token || !username) {
                alert('⚠️ 请先登录');
                window.location.href = '/login.html';
                return;
            }

            // 验证Token
            try {
                const response = await fetch(`${API_BASE_URL}/validate`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code !== 200) {
                    alert('⚠️ 登录已过期，请重新登录');
                    localStorage.clear();
                    window.location.href = '/login.html';
                    return;
                }
                
                // 获取用户级别
                const userLevel = result.data.userLevel || result.data.administrator || 0;
                currentUserLevel = parseInt(userLevel);
                
                // 检查是否为管理员或总管理员
                if (currentUserLevel < 1) {
                    alert('⚠️ 权限不足：只有管理员及以上级别可以创建用户');
                    window.location.href = '/home.html';
                    return;
                }
                
                // 显示当前用户信息和角色
                document.getElementById('currentUsername').textContent = username;
                const roleText = currentUserLevel == 2 ? '总管理员' : (currentUserLevel == 1 ? '管理员' : '子管理员');
                document.getElementById('currentUserRole').textContent = roleText;
                document.getElementById('currentUserInfo').style.display = 'block';
                
                // 只有总管理员(2)可以创建管理员
                if (currentUserLevel == 2) {
                    document.getElementById('adminOption').style.display = 'block';
                    document.getElementById('userTypeHint').textContent = '总管理员可以创建管理员和子管理员';
                } else {
                    document.getElementById('userTypeHint').textContent = '您只能创建子管理员';
                }
                
            } catch (error) {
                console.error('验证失败:', error);
                alert('⚠️ 验证失败，请重新登录');
                window.location.href = '/login.html';
            }
        }

        // 加载员工列表
        async function loadEmployees() {
            const token = localStorage.getItem('token');
            
            try {
                const response = await fetch(`${API_BASE_URL}/employees`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    employees = result.data;
                    const select = document.getElementById('employeeId');
                    select.innerHTML = '<option value="">-- 请选择员工 --</option>';
                    
                    employees.forEach(emp => {
                        const option = document.createElement('option');
                        option.value = emp.id;
                        // 显示格式：姓名 - 身份证号 - 部门 (已绑定)
                        option.textContent = `${emp.name} - ${emp.id_card} - ${emp.department || '未设置部门'}${emp.is_bound == 1 ? ' (已绑定)' : ''}`;
                        option.disabled = emp.is_bound == 1;
                        select.appendChild(option);
                    });
                } else {
                    showMessage('获取员工列表失败：' + result.message, 'error');
                }
            } catch (error) {
                console.error('获取员工列表失败:', error);
                showMessage('获取员工列表失败：' + error.message, 'error');
            }
        }

        // 用户类型切换
        document.getElementById('userType').addEventListener('change', (e) => {
            const isAdmin = e.target.value == '1';
            document.getElementById('normalUserFields').classList.toggle('hidden', isAdmin);
            document.getElementById('adminUserFields').classList.toggle('hidden', !isAdmin);
            document.getElementById('employeeInfo').style.display = 'none';
        });

        // 普通用户绑定方式切换
        document.getElementById('bindType').addEventListener('change', (e) => {
            const bindEmployee = e.target.value === 'employee';
            document.getElementById('bindEmployeeFields').classList.toggle('hidden', !bindEmployee);
            document.getElementById('manualInputFields').classList.toggle('hidden', bindEmployee);
            document.getElementById('employeeInfo').style.display = 'none';
        });

        // 员工选择变化
        document.getElementById('employeeId').addEventListener('change', (e) => {
            const empId = e.target.value;
            if (!empId) {
                document.getElementById('employeeInfo').style.display = 'none';
                return;
            }
            
            const employee = employees.find(emp => emp.id == empId);
            if (employee) {
                document.getElementById('employeeIdCard').textContent = employee.id_card;
                document.getElementById('employeeName').textContent = employee.name;
                document.getElementById('employeeDept').textContent = employee.department || '未设置';
                document.getElementById('employeePos').textContent = employee.position || '未设置';
                document.getElementById('employeeInfo').style.display = 'block';
            }
        });

        // 表单提交
        document.getElementById('createUserForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const token = localStorage.getItem('token');
            const userType = document.getElementById('userType').value;
            const isAdmin = userType == '1';
            
            let formData = {
                administrator: parseInt(userType),
                email: document.getElementById('email').value.trim(),
                phone: document.getElementById('phone').value.trim()
            };
            
            if (isAdmin) {
                // 管理员用户
                const username = document.getElementById('adminUsername').value.trim();
                const password = document.getElementById('adminPassword').value;
                const confirmPassword = document.getElementById('confirmPassword').value;
                
                if (!username || !password) {
                    showMessage('请填写用户名和密码', 'error');
                    return;
                }
                
                if (password !== confirmPassword) {
                    showMessage('两次输入的密码不一致', 'error');
                    return;
                }
                
                if (password.length < 6) {
                    showMessage('密码长度不能少于6位', 'error');
                    return;
                }
                
                formData.username = username;
                formData.password = password;
                formData.confirmPassword = confirmPassword;
            } else {
                // 普通用户：检查绑定方式
                const bindType = document.getElementById('bindType').value;
                
                if (bindType === 'employee') {
                    // 绑定员工
                    const employeeId = document.getElementById('employeeId').value;
                    
                    if (!employeeId) {
                        showMessage('请选择要绑定的员工', 'error');
                        return;
                    }
                    
                    formData.employeeId = parseInt(employeeId);
                } else {
                    // 手动输入
                    const username = document.getElementById('normalUsername').value.trim();
                    const password = document.getElementById('normalPassword').value;
                    const confirmPassword = document.getElementById('normalConfirmPassword').value;
                    
                    if (!username || !password) {
                        showMessage('请填写用户名和密码', 'error');
                        return;
                    }
                    
                    if (password !== confirmPassword) {
                        showMessage('两次输入的密码不一致', 'error');
                        return;
                    }
                    
                    if (password.length < 6) {
                        showMessage('密码长度不能少于6位', 'error');
                        return;
                    }
                    
                    formData.username = username;
                    formData.password = password;
                    formData.confirmPassword = confirmPassword;
                }
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/create`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                    body: JSON.stringify(formData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    let message = '✅ 用户创建成功！\n';
                    message += '用户名：' + result.data.username;
                    if (result.data.defaultPassword) {
                        message += '\n默认密码：' + result.data.defaultPassword;
                    }
                    message += '\n\n3秒后刷新页面...';
                    
                    showMessage(message, 'success');
                    
                    setTimeout(() => {
                        window.location.reload();
                    }, 3000);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                }
                
            } catch (error) {
                console.error('创建用户失败:', error);
                showMessage('❌ 创建用户失败：' + error.message, 'error');
            }
        });

        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.style.whiteSpace = 'pre-line';
            messageEl.className = `message ${type} show`;
            
            if (type === 'error') {
                setTimeout(() => {
                    messageEl.classList.remove('show');
                }, 5000);
            }
        }
    </script>
</body>
</html>

